package com.guys8.cemsbackend.controller;

import com.google.code.kaptcha.Producer;
import com.guys8.cemsbackend.DTO.Response;
import com.guys8.cemsbackend.DTO.UserInformation;
import com.guys8.cemsbackend.entity.Account;
import com.guys8.cemsbackend.entity.User;
import com.guys8.cemsbackend.service.impl.AccountServiceImpl;
import com.guys8.cemsbackend.service.impl.UserServiceImpl;
import com.guys8.cemsbackend.utils.JWTutil.JWTUtil;
import com.guys8.cemsbackend.utils.MD5.Md5util;
import com.guys8.cemsbackend.utils.RedisUtil.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;

@RestController
@Api(tags = "Account - 用户账号相关接口")
@RequestMapping("/account")
public class AccountContorller {

    @Autowired
    private AccountServiceImpl accountService;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private Producer captchaProducer;
    @Autowired
    RedisUtil redisUtil;


    @GetMapping("/getByAccountId/{accountid}")
    @ApiOperation("按accountId查找用户信息")
    public Response getInfoByUserId(@PathVariable Integer accountid) {
        Account account = accountService.getById(accountid);
        if(account == null) return Response.restResult(0);
        return Response.restResult(1,account);
    }

    @GetMapping("/getBySchoolId/{schoolid}")
    @ApiOperation("按schoolId查找用户信息")
    public Response getInfoByschoolId(@PathVariable String schoolid) {
        Account account = accountService.getbyschoolid(schoolid);
        if(account == null) return Response.restResult(0);
        return Response.restResult(1,account);
    }

    @GetMapping("/getByToken/")
    @ApiOperation("按schoolId查找用户信息(token)")
    public Response getInfoByToken(@RequestHeader String schoolid) {
        schoolid = JWTUtil.getUsername(schoolid);
        Account account = accountService.getbyschoolid(schoolid);
        if(account == null) return Response.restResult(0);
        return Response.restResult(1,account);
    }

    @PostMapping("/changePasw/private/{pasw_old}")
    @ApiOperation("比对密码(token)")
    public Response changePasw(@RequestHeader String schoolid,@PathVariable String pasw_old) {
        schoolid = JWTUtil.getUsername(schoolid);

        Account account = accountService.getbyschoolid(schoolid);
        //查询为空，返回为2为标记符
        if(account==null) return Response.restResult(2);

        String paswold = Md5util.inputPassToDbPass(pasw_old,account.getExt2());
        if (account.getPassword().equals(paswold)){
            //查询成功，返回1标记符
            return Response.restResult(1);
        } else {
            //比对不成功，用户旧密码输入错误，返回0
            return Response.restResult(0);
        }
    }

    @PostMapping("/makeAccount/{schoolid}&&{password}&&{permissions}")
    @ApiOperation("创建一个用户并返回（user,int）")
    public Response makeaAccount(@PathVariable String schoolid, @PathVariable String password, @PathVariable Integer permissions, HttpServletResponse response) {
        Account account = new Account(schoolid, password, permissions);
        if(accountService.getbyschoolid(schoolid)!=null){
            return Response.restResult(0);
        }
        accountService.save(account);
        //生成token
        String token= JWTUtil.sign(account.getSchoolId(),account.getPassword());
        response.setHeader("token",token);
        System.out.println(token);
        User user = new User(schoolid);
        userService.save(user);
        UserInformation userIn = new UserInformation(user);
        return Response.restResult(1,userIn,account.getPermissions());
    }

    @PostMapping("/loadAccount/{schoolid}&&{password}&&{validateCode}")
    @ApiOperation("用户登录接口登录成功返回（user,int）//1-管理员，2-教师，3-学生，4-其他")
    public Response loadAccount(@PathVariable String schoolid, @PathVariable String password, @PathVariable String validateCode, @RequestHeader String validateKey, HttpServletResponse response) {

        String validateCodeRedis= (String) redisUtil.get(validateKey);//拿到服务器端生成验证码的值
        if(!validateCode.equals(validateCodeRedis)){
            System.out.println(validateCode+"-"+validateCodeRedis);
            return Response.restResult(3);
        }
        Account account = accountService.getbyschoolid(schoolid);
        if(account == null) {
            return Response.restResult(2);
        }
        String salt = account.getExt2();
        String passBd = Md5util.inputPassToDbPass(password,salt);
        if(passBd.equals(account.getPassword())){
            String token= JWTUtil.sign(account.getSchoolId(),account.getPassword());
            response.setHeader("token",token);
            System.out.println(token);
            UserInformation userIn = new UserInformation(userService.getbyschoolid(schoolid));
            return Response.restResult(1,userIn,account.getPermissions());
        }else {
            return Response.restResult(0);
        }
    }

    @PostMapping("/changePasw/{pasw_old}&&{password}")
    @ApiOperation("更改密码(token)")
    public Response changePasw(@RequestHeader String schoolid, @PathVariable String pasw_old, @PathVariable String password) {

        schoolid = JWTUtil.getUsername(schoolid);

        Account account = accountService.getbyschoolid(schoolid);
        if(account==null) return Response.restResult(2);
        String paswold = Md5util.inputPassToDbPass(pasw_old,account.getExt2());
        if (account.getPassword().equals(paswold)){
            account.setPassword(Md5util.inputPassToDbPass(password,account.getExt2()));
        } else {
            return Response.restResult(0);
        }
        accountService.updateById(account);
        return Response.restResult(1);
    }

    @DeleteMapping("/logoutAccountbyId/")
    @ApiOperation("注销一个用户(token)")
    public Response logoutAccount(@RequestHeader String schoolid) {
        Account account = accountService.getbyschoolid(schoolid);
        if(account!=null) {
            accountService.removeById(account.getAccountId());
            return Response.restResult(1);
        }else {
            return Response.restResult(0);
        }
    }

    @PostMapping("/getKaptcha/")
    @ApiOperation("获取验证码")
    public Response changePasw(HttpServletResponse response) throws IOException {
        //生成验证码
        String capText = captchaProducer.createText();
        //把生成的验证码放入redis缓存:针对每个用户的验证码都会放入redis
        //每个用户的验证码跟validateId绑定
        String userValidateId = UUID.randomUUID().toString();
        System.out.println(capText+" "+userValidateId);
        //分布式缓存：所有客户端的信息都是放入redis
        //所有客户端生成的验证码都是放入redis
        redisUtil.set(userValidateId, capText);
        //把validateId发送给用户
        response.setHeader("validateKey", userValidateId);


        byte[] captcha = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        BufferedImage bi = captchaProducer.createImage(capText);
        ImageIO.write(bi,"jpg",out);

        captcha = out.toByteArray();
        Map<String,Object> map = new HashMap<>();
        Base64.Encoder encoder = Base64.getEncoder();
        map.put("captcha","data:image/jpg;base64,"+encoder.encodeToString(captcha));

        return Response.restResult(1,map);
    }


}